﻿using AutoMapper;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Write.Application.Common.Leave;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.Write.Application.Handler.Leave
{
    public class LeaveAddCommandHandle:IRequestHandler<LeaveAddCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<LeaveModel> LeaveDal;
        private readonly IMapper mapper;
        public LeaveAddCommandHandle(IBaseRepository<LeaveModel> leaveDal, IMapper mapper)
        {
            LeaveDal = leaveDal;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(LeaveAddCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            //var info = LeaveDal.GetAll().Where(x => x.LeaveName == request.LeaveName).FirstOrDefault();
            //if (info != null)
            //{
            //    res.Code = ApiEnum.Error;

            //    res.Message = "名称已存在";
            //    return Task.FromResult(res);
            //}

            var model = mapper.Map<LeaveModel>(request);
            model.CreateTime = DateTime.Now;
            var r = 0;
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                r = LeaveDal.Add(model).Result;
                tran.Complete();
            };

            if (r > 0)
            {
                res.Code = ApiEnum.Success;
                res.Data = r;
                res.Message = "添加成功";
                return Task.FromResult(res);
            }
            else
            {
                res.Code = ApiEnum.Error;
                res.Data = r;
                res.Message = "添加失败";
                return Task.FromResult(res);
            }
        }
    }
}
